package com.hdjk.view.activity.personalcenter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.liangmutian.mypicker.DateUtil;
import com.hdjk.view.R;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.entity.FundEntity;
import com.hdjk.view.entity.Performance;
import com.hdjk.view.entity.WalletHoldingEntity;
import com.hdjk.view.network.WalletNetWork;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by sxy on 2017/11/15.
 */

public class WalletActivity extends BaseActivity implements View.OnClickListener ,SwipeRefreshLayout.OnRefreshListener{
    private JSONObject perjson;
    private FundEntity mFund;
    private WalletHoldingEntity mWalletHolding;
    private boolean load1=false,load2=false;
    // Content View Elements
    private android.support.v4.widget.SwipeRefreshLayout swipe_ly;
    private ImageView iv_back;
    private TextView tv_detail;
    private TextView tv_assets;
    private TextView tv_year_profit;
    private LinearLayout lin_profit;
    private TextView tv_yesterday;
    private TextView tv_sum;
    private WebView wv_chart;
    private TextView tv_take;
    private TextView tv_recharge;
    // End Of Content View Elements

    private void bindViews() {
        swipe_ly = (android.support.v4.widget.SwipeRefreshLayout) findViewById(R.id.swipe_ly);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_detail = (TextView) findViewById(R.id.tv_detail);
        tv_assets = (TextView) findViewById(R.id.tv_assets);
        tv_year_profit = (TextView) findViewById(R.id.tv_year_profit);
        lin_profit = (LinearLayout) findViewById(R.id.lin_profit);
        tv_yesterday = (TextView) findViewById(R.id.tv_yesterday);
        tv_sum = (TextView) findViewById(R.id.tv_sum);
        wv_chart = (WebView) findViewById(R.id.wv_chart);
        tv_take = (TextView) findViewById(R.id.tv_take);
        tv_recharge = (TextView) findViewById(R.id.tv_recharge);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_wallet);
        bindViews();
        iv_back.setOnClickListener(this);
        tv_detail.setOnClickListener(this);
        lin_profit.setOnClickListener(this);
        tv_take.setOnClickListener(this);
        tv_recharge.setOnClickListener(this);
        swipe_ly.setOnRefreshListener(this);
        swipe_ly.setColorSchemeResources(R.color.bg_common_red, R.color.bg_common_red,
                R.color.bg_common_red, R.color.bg_common_red);
        // 设置手指在屏幕下拉多少距离会触发下拉刷新
        swipe_ly.setDistanceToTriggerSync(200);
    }

    @Override
    protected void initData() {
        initWebView();
        getWalletFund();
        getWalletHoldings();
    }

    private void getWalletFund() {
        if (!mDialog.isShowing())
            mDialog.show();
        WalletNetWork.getWalletFund(UserTokenUtil.getToken(WalletActivity.this), new CallBackListener() {
            @Override
            public void onCallBackCompleted(Msg msg) {
                load1=true;
                if (mDialog.isShowing()&&load1&&load2) {
                    mDialog.dismiss();
                }
                if (swipe_ly.isRefreshing()&&load1&&load2){
                    swipe_ly.setRefreshing(false);
                }
                if (msg != null && msg.getSuccess() && msg.getData() != null) {
                    mFund = (FundEntity) msg.getData();
                    tv_year_profit.setText("七日年化：" + mFund.getSevenDaysAnnualizedYield() + "%");
                }
            }

            @Override
            public void onCallBackError(Msg msg) {

            }
        });
    }

    private void getWalletHoldings() {
        if (!mDialog.isShowing())
            mDialog.show();
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(this));
            WalletNetWork.getWalletHoldings(UserTokenUtil.getToken(this), obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    load2=true;
                    if (mDialog.isShowing()&&load1&&load2) {
                        mDialog.dismiss();
                    }
                    if (swipe_ly.isRefreshing()&&load1&&load2){
                        swipe_ly.setRefreshing(false);
                    }
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof WalletHoldingEntity) {
                        mWalletHolding = (WalletHoldingEntity) msg.getData();
                        if (!TextUtils.isEmpty(mWalletHolding.getPreProfitLoss()) && !"null".equals(mWalletHolding.getPreProfitLoss()))
                            tv_yesterday.setText(mWalletHolding.getPreProfitLoss());
                        if (!TextUtils.isEmpty(mWalletHolding.getTotalCurrentValue()) && !"null".equals(mWalletHolding.getTotalCurrentValue()))
                            tv_assets.setText(mWalletHolding.getTotalCurrentValue());
                        if (!TextUtils.isEmpty(mWalletHolding.getProfitLoss()) && !"null".equals(mWalletHolding.getProfitLoss()))
                            tv_sum.setText(mWalletHolding.getProfitLoss());
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("JavascriptInterface")
    private WebView initWebView() {
        wv_chart = (WebView) findViewById(R.id.wv_chart);
        WebSettings setting = wv_chart.getSettings();
        // 安全考虑
        // 密码不保存,默认会弹出对话框
        setting.setSavePassword(false);

        setting.setSupportZoom(true);//缩放开关
        setting.setBuiltInZoomControls(true);//设置是否可缩放
        setting.setDisplayZoomControls(false);

        //自适应屏幕
        setting.setUseWideViewPort(true);//设置webview推荐使用的窗口，设置为true，无限缩放，就需要使用大视图模式
        setting.setLoadWithOverviewMode(true);//设置webview加载的页面的模式，也设置为true。

        // 设置缓存
//		setting.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 取消缓存
        setting.setCacheMode(WebSettings.LOAD_NO_CACHE);

        setting.setAllowFileAccess(true);
        setting.setAppCacheEnabled(true);
//        setting.setAllowUniversalAccessFromFileURLs(true);

        // 支持javascript
        setting.setJavaScriptEnabled(true);
        wv_chart.addJavascriptInterface(this, "javatojs");

        //最重要的方法，一定要设置数据缓存，这就是出不来的主要原因
        setting.setDomStorageEnabled(true);
        //启用数据库
        setting.setDatabaseEnabled(true);

        //启用地理定位
        setting.setGeolocationEnabled(true);
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        //设置定位的数据库路径
        setting.setGeolocationDatabasePath(dir);

        wv_chart.loadUrl("file:///android_asset/echarts.html");

        wv_chart.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                getPerfromanceChart(perjson);
            }
        });
        return wv_chart;
    }


    private void getPerfromanceChart(JSONObject json) {
        try {
            if (wv_chart != null && null != json) {
                wv_chart.loadUrl("javascript:initChart('" + json.toString() + "')");
                return;
            }

            if (!mDialog.isShowing())
                mDialog.show();

            JSONObject object = new JSONObject();
            object.put("startDate", DateUtil.getYestMonthDate());
//            object.put("startDate", "2017-11-05");
            object.put("endDate", DateUtil.getToday());
            object.put("pageSize", 100);
            object.put("pageIndex", 1);
            WalletNetWork.getWalletHistoricalData(UserTokenUtil.getToken(WalletActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    if (mDialog.isShowing()&&load1&&load2) {
                        mDialog.dismiss();
                    }
                    if (msg != null && msg.getSuccess()) {
                        List<Performance> list;
                        if (msg.getData()!=null&&msg.getData() instanceof List){
                            list = (List<Performance>) msg.getData();
                        }else {
                            list=new ArrayList<>();
                        }
                        showChart(list);
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void showChart(List<Performance> list) {
        Collections.sort(list, new Comparator<Performance>() {
            @Override
            public int compare(Performance performance, Performance t1) {
                return performance.getNavDate().compareTo(t1.getNavDate());
            }
        });
        if (list != null) {
            JSONObject jsonObject = new JSONObject();
            try {
                JSONArray legendArray = new JSONArray();
                JSONArray xDataArray = new JSONArray();
                JSONArray yDataArray = new JSONArray();
                JSONArray yDataArray1 = new JSONArray();

                legendArray.put(new JSONObject().put("legend", "万份收益(元)"));
                jsonObject.put("legend", legendArray);

                for (Performance performance : list) {
                    JSONObject xData = new JSONObject();
                    xData.put("time", DateUtil.formatDate(Long.parseLong(performance.getNavDate()), "yyyy-MM-dd"));
                    JSONObject yData = new JSONObject();
                    yData.put("data", performance.getEarningsPer10000());

                    xDataArray.put(xData);
                    yDataArray1.put(yData);
                }
                yDataArray.put(yDataArray1);
                jsonObject.put("xData", xDataArray);
                jsonObject.put("yData", yDataArray);
                wv_chart.loadUrl("javascript:initChart('" + jsonObject.toString() + "')");
                perjson = jsonObject;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                back();
                break;
            case R.id.tv_detail:
                intent = new Intent(this, WalletTransactionListActivity.class);
                startActivity(intent);
                break;
            case R.id.lin_profit:
                intent = new Intent(this, WalletProfitListActivity.class);
                intent.putExtra("sum",tv_sum.getText().toString());
                startActivity(intent);
                break;
            case R.id.tv_take:
                intent = new Intent(this, WalletTakeActivity.class);
                intent.putExtra("money",mWalletHolding!=null?mWalletHolding.getAvailableValue():"0.00");
                startActivityForResult(intent, 111);
                break;
            case R.id.tv_recharge:
                intent = new Intent(this, WalletRechargeActivity.class);
                startActivityForResult(intent, 222);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 222 && resultCode == 333) {//充值
            getWalletHoldings();
        }
        if (requestCode == 111 && requestCode == 111) {//取现
            getWalletHoldings();
        }
    }

    @Override
    public void onRefresh() {
        getWalletFund();
        getWalletHoldings();
    }
}
